#include "widget_funcb_smart_vision.h"
#include "ui_widget_funcb_smart_vision.h"
#include <QDebug>
#include <QPixmap>
#include <QTimer>
#include <QSslSocket>
#include <QTextCodec>

// ---------------- Widget_funcB_Smart_vision 实现 ----------------
Widget_funcB_Smart_vision::Widget_funcB_Smart_vision(QWidget *parent)
    : QWidget(parent)
{
    ui = new Ui::Widget_funcB_Smart_vision;
    ui->setupUi(this);

    // 你的按钮连接（保持原有逻辑）
    connect(ui->label_return_home, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_button_start);
    connect(ui->label_run_home, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_button_start);
    connect(ui->button_sleep, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_sleep_get_up);
    connect(ui->button_get_up, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_sleep_get_up);
    connect(ui->button_air_conditioner, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_air_conditioner);
    connect(ui->button_tv, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_tv);
    connect(ui->button_robot, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_robot);
    connect(ui->button_toaster, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_toaster);
    connect(ui->button_washing_machine, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_washing_machine);
    connect(ui->button_wifi, &Button_home_start::signals_start, this, &Widget_funcB_Smart_vision::slots_wifi);

    // --- ✅ 新增：TCP 客户端初始化 ---
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, &QTcpSocket::readyRead, this, &Widget_funcB_Smart_vision::onReadyRead);
    connect(tcpSocket, &QTcpSocket::disconnected, this, &Widget_funcB_Smart_vision::onDisconnected);
    connectToServer();

    // --- 初始化设备图标（使用你资源路径 :/img/xxxx.png 和 :/img/xxxx1.png） ---
    // 默认均为关闭状态（如果你想启动时某些为开，修改对应 bool 变量）
    air_on = false;
    tv_on = false;
    robot_on = false;
    toaster_on = false;
    washing_on = false;
    wifi_on = false;

    updateDeviceIcon(ui->label_13, "air_conditation", air_on); // 空调 -> label_11
    updateDeviceIcon(ui->label_14, "bread", toaster_on);       // 烤面包机 -> label_12
    updateDeviceIcon(ui->label_15, "tv", tv_on);               // 电视 -> label_13
    updateDeviceIcon(ui->label_16, "wash", washing_on);        // 洗衣机 -> label_14
    updateDeviceIcon(ui->label_17, "robot", robot_on);         // 机器人 -> label_15
    updateDeviceIcon(ui->label_18, "wifi", wifi_on);           // WiFi -> label_16

    // --- home/led 默认亮 ---
    home_on = true;
    led_on = true;
    initSpecialIcons();

    // --- 绑定 home/led 按钮切换图标 ---
    connect(ui->label_return_home, &Button_home_start::signals_start, this, [=](bool start){
        home_on = start;
        updateSpecialIcon(ui->label_19, "home", home_on);
    });
    connect(ui->label_run_home, &Button_home_start::signals_start, this, [=](bool start){
        home_on = start;
        updateSpecialIcon(ui->label_19, "home", home_on);
    });
    connect(ui->button_sleep, &Button_home_start::signals_start, this, [=](bool start){
        led_on = start;
        updateSpecialIcon(ui->label_21, "led", led_on);
    });
    connect(ui->button_get_up, &Button_home_start::signals_start, this, [=](bool start){
        led_on = start;
        updateSpecialIcon(ui->label_21, "led", led_on);
    });
}

Widget_funcB_Smart_vision::~Widget_funcB_Smart_vision()
{
    delete ui;
}

// 其余智能家居槽按你原逻辑保持
void Widget_funcB_Smart_vision::slots_button_start(bool start)
{
    QObject * temp = sender();
    if(temp == ui->label_run_home)
    {
        ui->label_run_home->set_start(start);
        ui->label_return_home->set_start(!start);
    }
    if(temp == ui->label_return_home)
    {
        ui->label_return_home->set_start(start);
        ui->label_run_home->set_start(!start);
    }
}

void Widget_funcB_Smart_vision::slots_sleep_get_up(bool start)
{
    QObject *temp = sender();
    if (temp == ui->button_sleep)
    {
        ui->button_sleep->set_start(start);
        ui->button_get_up->set_start(!start);
    }
    if (temp == ui->button_get_up)
    {
        ui->button_get_up->set_start(start);
        ui->button_sleep->set_start(!start);
    }
}

void Widget_funcB_Smart_vision::connectToServer()
{
    if (tcpSocket->state() == QAbstractSocket::ConnectedState)
        return;

    qDebug() << "正在连接服务器..." << serverIP << ":" << serverPort;
    tcpSocket->connectToHost(QHostAddress(serverIP), serverPort);

    if (!tcpSocket->waitForConnected(3000)) {
        qDebug() << "连接服务器失败：" << tcpSocket->errorString();
    } else {
        qDebug() << "✅ 已连接服务器";
    }
}

void Widget_funcB_Smart_vision::onDisconnected()
{
    qDebug() << "⚠️ 服务器连接断开，尝试重连...";
    QTimer::singleShot(2000, this, &Widget_funcB_Smart_vision::connectToServer);
}

void Widget_funcB_Smart_vision::sendMessage(const QString &msg)
{
    if (tcpSocket->state() != QAbstractSocket::ConnectedState) {
        connectToServer();
        qDebug() << "服务器未连接，正在重连...";
        return;
    }

    QTextCodec *codec = QTextCodec::codecForName("GBK");  // 转GBK编码
    QByteArray data = codec->fromUnicode(msg + "\r\n");    // 加上换行，调试助手友好显示
    tcpSocket->write(data);
    tcpSocket->flush();
    qDebug() << "📤 已发送消息：" << msg;
}

void Widget_funcB_Smart_vision::onReadyRead()
{
    QByteArray data = tcpSocket->readAll();
    QTextCodec *codec = QTextCodec::codecForName("GBK");  // 按GBK解析
    QString msg = codec->toUnicode(data).trimmed();

    handleReceivedCommand(msg);
}


void Widget_funcB_Smart_vision::handleReceivedCommand(const QString &msg)
{
    QString text = msg;
    text.replace("\r", "").replace("\n", "").replace(" ", "");

    qDebug() << "📩 处理指令:" << text;

    bool on = false;
    if (text.contains(QRegExp("开|开启"))) on = true;
    if (text.contains(QRegExp("关|关闭"))) on = false;

    if (text.contains("空调")) ui->button_air_conditioner->set_start(on);
    else if (text.contains("电视")) ui->button_tv->set_start(on);
    else if (text.contains("机器人")) ui->button_robot->set_start(on);
    else if (text.contains("烤面包机")) ui->button_toaster->set_start(on);
    else if (text.contains("洗衣机")) ui->button_washing_machine->set_start(on);
    else if (text.contains("WIFI") || text.contains("wifi")) ui->button_wifi->set_start(on);
    else qDebug() << "⚠️ 未匹配到已知设备";
}

// ---------------- 家居功能按钮槽修改（增加图片切换逻辑） ----------------
void Widget_funcB_Smart_vision::slots_air_conditioner(bool start)
{
    QString msg = QString("空调: %1").arg(start ? "开启" : "关闭");
    sendMessage(msg);
    qDebug() << msg;

    // 更新状态与图片（label_11 显示空调图）
    air_on = start;
    updateDeviceIcon(ui->label_13, "air_conditation", air_on);
}

void Widget_funcB_Smart_vision::slots_tv(bool start)
{
    QString msg = QString("电视: %1").arg(start ? "开启" : "关闭");
    sendMessage(msg);
    qDebug() << msg;

    tv_on = start;
    updateDeviceIcon(ui->label_15, "tv", tv_on);
}

void Widget_funcB_Smart_vision::slots_robot(bool start)
{
    QString msg = QString("机器人: %1").arg(start ? "开启" : "关闭");
    sendMessage(msg);
    qDebug() << msg;

    robot_on = start;
    updateDeviceIcon(ui->label_17, "robot", robot_on);
}

void Widget_funcB_Smart_vision::slots_toaster(bool start)
{
    QString msg = QString("烤面包机: %1").arg(start ? "开启" : "关闭");
    sendMessage(msg);
    qDebug() << msg;

    toaster_on = start;
    updateDeviceIcon(ui->label_14, "bread", toaster_on);
}

void Widget_funcB_Smart_vision::slots_washing_machine(bool start)
{
    QString msg = QString("洗衣机: %1").arg(start ? "开启" : "关闭");
    sendMessage(msg);
    qDebug() << msg;

    washing_on = start;
    updateDeviceIcon(ui->label_16, "wash", washing_on);
}

void Widget_funcB_Smart_vision::slots_wifi(bool start)
{
    QString msg = QString("WIFI: %1").arg(start ? "开启" : "关闭");
    sendMessage(msg);
    qDebug() << msg;

    wifi_on = start;
    updateDeviceIcon(ui->label_18, "wifi", wifi_on);
}

void Widget_funcB_Smart_vision::slots_button_send_message()
{
    // 预留函数
}

void Widget_funcB_Smart_vision::updateDeviceIcon(QLabel *label, const QString &baseName, bool on)
{
    if (!label) return;

    // 资源路径模式：开 -> :/img/xxx.png  关 -> :/img/xxx1.png
    QString path = QString(":/img/%1%2.png").arg(baseName).arg(on ? "" : "1");
    QPixmap pix(path);

    if (pix.isNull()) {
        qWarning() << "❌ 设备图片未找到:" << path;
        return;
    }

    // 将白色背景处理为透明
    QImage img = pix.toImage().convertToFormat(QImage::Format_ARGB32);
    for (int y = 0; y < img.height(); ++y) {
        for (int x = 0; x < img.width(); ++x) {
            QColor c = img.pixelColor(x, y);
            if (c.red() > 240 && c.green() > 240 && c.blue() > 240) { // 近似白色
                c.setAlpha(0);
                img.setPixelColor(x, y, c);
            }
        }
    }
    pix = QPixmap::fromImage(img);

    // 保持比例缩放到 QLabel
    label->setPixmap(pix.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
    label->setScaledContents(false);
}

// 更新房子和灯泡图标的函数
void Widget_funcB_Smart_vision::updateSpecialIcon(QLabel *label, const QString &baseName, bool on)
{
    if (!label) return;

    // 资源路径规则：亮的 -> :/img/home.png, 灰的 -> :/img/home1.png
    QString path = QString(":/img/%1%2.png").arg(baseName).arg(on ? "" : "1");
    QPixmap pix(path);

    if (pix.isNull()) {
        qWarning() << "❌ 特殊设备图片未找到:" << path;
        return;
    }

    // 将白色背景处理为透明
    QImage img = pix.toImage().convertToFormat(QImage::Format_ARGB32);
    for (int y = 0; y < img.height(); ++y) {
        for (int x = 0; x < img.width(); ++x) {
            QColor c = img.pixelColor(x, y);
            if (c.red() > 240 && c.green() > 240 && c.blue() > 240) { // 白色透明
                c.setAlpha(0);
                img.setPixelColor(x, y, c);
            }
        }
    }
    pix = QPixmap::fromImage(img);

    // 保持比例缩放
    label->setPixmap(pix.scaled(label->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
    label->setScaledContents(false);
}

// 点击按钮或者切换状态时调用
void Widget_funcB_Smart_vision::toggleHome()
{
    home_on = !home_on;
    updateSpecialIcon(ui->label_19, "home", home_on);
}

void Widget_funcB_Smart_vision::toggleLed()
{
    led_on = !led_on;
    updateSpecialIcon(ui->label_21, "led", led_on);
}

// 初始化时设置默认亮
void Widget_funcB_Smart_vision::initSpecialIcons()
{
    updateSpecialIcon(ui->label_19, "home", home_on);
    updateSpecialIcon(ui->label_21, "led", led_on);
}
